package com.zhang.zhangapp.view.shop;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.RatingBar;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.zhang.zhangapp.R;
import com.zhang.zhangapp.application.MApplication;
import com.zhang.zhangapp.base.config.HttpConfig;
import com.zhang.zhangapp.base.http.MCallback;
import com.zhang.zhangapp.http.CommonHttp;
import com.zhang.zhangapp.http.UpLoadHttp;
import com.zhang.zhangapp.utils.PicassoImageLoader;
import com.zhang.zhangapp.utils.T;
import com.zhang.zhangapp.view.BaseAppCompatActivityActivity;
import com.zhang.zhangapp.view.adapter.UserCommentImageAdapter;
import com.zhang.zhangapp.view.custom.WrapHeightGridView;

import org.xutils.common.Callback;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/4/21.
 */
@ContentView(R.layout.activity_comment)
public class UserCommentActivity extends BaseAppCompatActivityActivity {
    private final static int IMAGE_PICKER = 10002;
    @ViewInject(R.id.rb)
    RatingBar ratingBar;
    @ViewInject(R.id.comment_text)
    EditText commentEdit;
    @ViewInject(R.id.comment_gridview)
    WrapHeightGridView gridView;

    UserCommentImageAdapter userCommentImageAdapter;

    List<ImageItem> imageItems = new ArrayList<>();
    ImagePicker imagePicker;

    List<ImageItem> uploadImages;

    private String shopCode;

    private String picUrls;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        shopCode = getIntent().getStringExtra("shopCode");
        initView();
        initImagePicker();
    }

    private void initImagePicker() {
        imagePicker = ImagePicker.getInstance();
        imagePicker.clear();
        imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setMultiMode(true);
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(4);    //选中数量限制
    }

    private void initView() {
        ImageItem imageItem = new ImageItem();
        imageItem.path = "path";
        imageItems.add(imageItem);
        userCommentImageAdapter = new UserCommentImageAdapter(imageItems, this);
        gridView.setAdapter(userCommentImageAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == (imageItems.size() - 1)) {
                    Intent intent = new Intent(UserCommentActivity.this, ImageGridActivity.class);
                    startActivityForResult(intent, IMAGE_PICKER);
                } else {
                    Intent intent = new Intent(UserCommentActivity.this, ImagePreviewActivity.class);
                    intent.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, 0);
                    intent.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, imagePicker.getSelectedImages());
                    intent.putExtra(ImagePreviewActivity.ISORIGIN, false);
                    intent.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                    startActivityForResult(intent, ImagePicker.REQUEST_CODE_PREVIEW);
                }
            }
        });
    }

    @Event(R.id.comment_sure)
    private void addComment(View view) {
        if ("".equals(commentEdit.getText().toString())) {
            T.showShort(this, "请填写评价");
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("shopCode", shopCode);
        params.put("memberId", MApplication.getInstance().getUser().getMemberId());
        params.put("descr", commentEdit.getText().toString());
        params.put("score", ratingBar.getNumStars() + "");
        params.put("picurls", picUrls);

        CommonHttp.commonHttp("hzg/shop/addEvaluate", params, new MCallback() {
            @Override
            public void onSuccess(String data) {
                T.showShort(UserCommentActivity.this, "评论成功");
                UserCommentActivity.this.finish();
            }

            @Override
            public void onSuccess(String message, String code) {

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            uploadImages = (ArrayList<ImageItem>) data.getSerializableExtra("extra_result_items");
            if (uploadImages != null) {
                uploadFile(0);
                imageItems.addAll(0, uploadImages);
                userCommentImageAdapter.notifyDataSetChanged();
            }
        }
    }

    int curUploadIndex;

    private void uploadFile(int index) {
        curUploadIndex = index;
        if (curUploadIndex < uploadImages.size()) {
            if (showLoadingDialog()) {
                UpLoadHttp.upLoadFile(uploadImages.get(index).path, new MCallback() {
                    @Override
                    public void onSuccess(String data) {
                        if (picUrls == null) {
                            picUrls = data;
                        } else {
                            picUrls += "," + data;
                        }
                    }

                    @Override
                    public void onSuccess(String message, String code) {

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(Callback.CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {
                        uploadFile(curUploadIndex + 1);
                    }
                });
            }
        } else {
            dismisionDalog();
        }
    }
}
